﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model;
using Bll;
using Common;
using Web.Extension;
using Microsoft.AspNetCore.Authorization;
using Web.Controllers;
using Web.Filter;
using Web.Util;
using System.Data;
using Microsoft.EntityFrameworkCore;
using Common.Util;
using static Model.Interview;
using System.Collections;

namespace Web.Teach.Controllers
{
    [Route("api/teach/[controller]/[action]")]
    [ApiController]
    [Authorize("teacher")]
    [QueryFilter]
    public class InterviewController : MyBaseController<Interview>
    {
        IInterviewBll bll;
        public  INoticeBll noticeBll { get; set; }
        public InterviewController(IInterviewBll bll)
        {
            this.bll = bll;
        }
        // GET: api/List/Interview
        [HttpGet]
        public Result List([FromQuery] Dictionary<string, string> where)
        {
            where.Remove("TeacherId");
            //return Result.Success("succeed").SetData(bll.SelectAll(o => true, pageNo, pageSize));
            return Result.Success("succeed").SetData(bll.Query(where));
        }
        /// <summary>
        /// 根据公司id查询应聘记录
        /// </summary>
        /// <param name="companyId"></param>
        /// <returns></returns>
        [HttpGet]
        public Result ListOfCompany(int companyId)
        {
            return Result.Success("succeed").SetData(bll.SelectAll(o => o.Post.CompanyId == companyId));
        }
        // GET: api/Interview/Get/5
        [HttpGet("{id}")]
        public Result Get([FromQuery] Dictionary<string, string> where)
        {
            return Result.Success("succeed").SetData(bll.SelectOne(where));
        }
        // POST: api/Interview/Add
        [HttpPost]
        public Result Add(Interview o)
        {
            return ModelState.IsValid ? (bll.Add(o) ? Result.Success("添加成功") : Result.Error("添加失败")) : Result.Error("添加失败!" + ModelState.GetAllErrMsgStr(";")); ;
        }

        // Post: api/Interview/Update
        [HttpPost]
        public Result Update(Interview o)
        {
            return ModelState.IsValid ? (bll.Update(o) ? Result.Success("修改成功").SetData(o) : Result.Error("修改失败")) : Result.Error("修改失败!" + ModelState.GetAllErrMsgStr(";")); ;
        }

        // Get: api/Interview/Delet/5
        [HttpGet("{id}")]
        public Result Delete([FromQuery] Dictionary<string, string> where)
        {
            return bll.Delete(where) ? Result.Success("删除成功") : Result.Error("删除失败");
        }
        [HttpPost]
        public Result BatchDelete([FromForm] Dictionary<string, string> where)
        {
            return bll.Delete(where) ? Result.Success("删除成功") : Result.Error("删除失败");
        }
        /// <summary>
        /// 操作面试结果
        /// </summary>
        /// <param name="interviewId"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        [HttpPost]
        public Result Op([FromForm] int interviewId, [FromForm] InterviewStatus status)
        {
           // Interview i = bll.DbContext().Interviews.Include("Student").Include("Post").Include("Post.Company").FirstOrDefault(o => o.Id == interviewId);
           Interview i = bll.SelectOne(interviewId);
            i.Status = status;
            bll.Update(i);
            if (i.Status == InterviewStatus.Passed)//面试通过，加入公告
            {
                Notice o = new Notice() {Name="校园招聘",Text=$"恭喜{i.Student.Realname}被{i.Post.Company.Name}录取!" };
                noticeBll.Add(o);
            }
            return Result.Success("操作成功!"); ;
        }
        /// <summary>
        /// 导出面试记录为excel
        /// </summary>
        /// <param name="companyId">公司id</param>
        /// <param name="top">导出多少条</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ExportToExcel(int? companyId, int? top)
        {
            var st = OfficeHelper.DataTableToExcel(CreateTable(companyId, top));
            //string filePath = DataTableToExcel(CreateTable());
            // FileStream fs = new FileStream(filePath, FileMode.Open);
            //return File(fs, "application/vnd.ms-excel", "异地派遣面试记录表.xls");
            //var provider = new FileExtensionContentTypeProvider();
            //var memi = provider.Mappings[fileExt];
            //FileStreamResult fileStreamResult = new FileStreamResult(stream, memi) { FileDownloadName = fileName };

            return File(st, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "面试记录表.xlsx");
        }

        private DataTable CreateTable(int? companyId, int? top)
        {
            var db = bll.DbContext();
            var query = (from p in db.Posts
                         join c in db.Companys on p.CompanyId equals c.Id into companies
                         from company in companies.DefaultIfEmpty()
                         join it in db.Interviews on p.Id equals it.PostId into interviews
                         from interview in interviews.DefaultIfEmpty()
                         join s in db.Students on interview.StudentId equals s.Id into students
                         from student in students.DefaultIfEmpty()
                         where p.TeacherId == MyUser.Id && (companyId == null || p.CompanyId == companyId)
                         orderby p.CompanyId descending, p.Added_time descending, interview.Added_time descending, student.Classs.Id ascending
                         select new
                         {
                             CompanyName = company.Name,
                             PostName = p.Name,
                             StudentName = student.Realname,
                             Gender = student.Gender == null ? "未知" : student.Gender.GetText(),
                             ClassName = student.Classs.Name,
                             PostTime = p.Added_time,
                             ResumeTime = interview.Added_time,
                             Salary = p.Salary
                         });
            if (top != null && top != 0)
            {
                query = query.Take((int)top);
            }
            var objs = query.ToList();
            return CreateTable(query);

            //List<Interview> objs = db.Interviews.Where(o => o.Post.TeacherId == MyUser.Id).OrderByDescending(t => t.Post.CompanyId).Include("Post").Include("Student").ToList();            
        }
        //创建DataTable 方法 
        private DataTable CreateTable(IEnumerable query)
        {

            string[] Headers = { "ID", "公司名称", "应聘岗位", "薪资", "职位发布时间", "报名面试者", "性别", "班级", "报名时间" };
            DataTable dataTable = new DataTable("ExportData");//*新建一张表
            foreach (string TemStr in Headers)
            {
                DataColumn strNameColumn = new DataColumn();
                strNameColumn.DataType = typeof(String);
                strNameColumn.ColumnName = TemStr;
                dataTable.Columns.Add(strNameColumn);       //*建立五列数据
            }
            int i = 0;
            foreach (var o in query)
            {
                i = i + 1;
                //Interview o = objs[i];
                //Student s = db.Student.Where(t => t.id == o.student.id).Include("classs").FirstOrDefault();
                DataRow rowData = dataTable.NewRow();   //*建立行数据
                rowData["ID"] = (i).ToString();
                rowData["报名面试者"] = o.GetType().GetProperty("StudentName")?.GetValue(o)?.ToString();
                rowData["性别"] = o.GetType().GetProperty("Gender")?.GetValue(o)?.ToString();
                rowData["班级"] = o.GetType().GetProperty("ClassName")?.GetValue(o)?.ToString();
                rowData["报名时间"] = o.GetType().GetProperty("ResumeTime")?.GetValue(o)?.ToString();
                rowData["公司名称"] = o.GetType().GetProperty("CompanyName")?.GetValue(o)?.ToString();
                rowData["应聘岗位"] = o.GetType().GetProperty("PostName")?.GetValue(o)?.ToString();
                rowData["薪资"] = o.GetType().GetProperty("Salary")?.GetValue(o)?.ToString();
                rowData["职位发布时间"] = o.GetType().GetProperty("PostTime")?.GetValue(o)?.ToString();
                //DataRow rowData = dataTable.NewRow();   //*建立行数据
                //rowData["ID"] = (i + 1).ToString();
                //rowData["姓名"] = o.Student.Realname;
                //rowData["性别"] = o.Student.Gender.GetText();
                //rowData["班级"] = o.Student.Classs.Name;
                ////rowData["面试时间"] = o.interview_time;
                //rowData["公司名称"] = o.Post.Company.Name;
                //rowData["应聘岗位"] = o.Post.Name;
                //rowData["薪资"] = o.Post.Salary;
                //rowData["报名时间"] = o.Added_time;
                dataTable.Rows.Add(rowData);
            }
            //List<Interview> objs = db.Interviews.Where(o => o.Post.TeacherId == MyUser.Id).OrderByDescending(t => t.Post.CompanyId).Include("Post").Include("Student").ToList();            
            return dataTable;
        }
    }
}
